package io.gitee.dtdage.app.boot.starter.data.storage.service.impl;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import io.gitee.dtdage.app.boot.starter.data.storage.context.Configure;
import io.gitee.dtdage.app.boot.starter.data.storage.enums.Supplier;
import io.gitee.dtdage.app.boot.starter.data.storage.service.ConfigureService;
import io.gitee.dtdage.app.boot.starter.data.storage.service.StorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * 七牛云对象存储实现类
 *
 * @author WFT
 * @noinspection SpellCheckingInspection
 * @since 2024/4/14
 */
@Service
@RequiredArgsConstructor
public class QiniuStorageServiceImpl implements StorageService {

    private final ConfigureService<?> configureService;

    @Override
    public Supplier getId() {
        return Supplier.qiniu_cloud;
    }

    @Override
    public void delete(String path) throws Exception {
        //  获取存储桶配置
        Configure configure = this.configureService.getConfigure(this.getId());
        //  创建访问令牌
        Auth auth = Auth.create(configure.getSecretId(), configure.getSecretKey());
        //  调用删除文件接口
        new BucketManager(auth, new Configuration(Region.autoRegion())).delete(configure.getBucketName(), path);
    }

    @Override
    public String upload(InputStream stream, String filename, String suffix) throws Exception {
        //  获取存储桶配置
        Configure configure = this.configureService.getConfigure(this.getId());
        //  创建访问令牌
        String token = Auth.create(configure.getSecretId(), configure.getSecretKey()).uploadToken(configure.getBucketName());
        //  创建SDK配置
        Configuration configuration = new Configuration(Region.autoRegion());
        //  指定分片上传版本
        configuration.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        //  调用上传文件接口
        new UploadManager(configuration).put(stream, filename + suffix, token, null, null);
        //  返回访问路径
        return configure.getProxyPath() + filename + suffix;
    }

}
